from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker

from commons.entity.po.reimbursement_approval_ma import ReimbursementApprovalMa
from commons.mappers.base_mapper import BaseMapper

# 创建数据库引擎
db_url = "mysql+pymysql://root:123456@localhost/ctdb"
engine = create_engine(db_url, echo=True)

# 创建会话类
Session = sessionmaker(bind=engine)


class ReimbursementApprovalMaMapper(BaseMapper):
    def __init__(self):
        super().__init__(Session)

    def select_by_reimbursement_approval_ma_id(self, reimbursement_approval_ma_id):
        """
        根据 reimbursement_approval_ma_id 从数据库获取 经理审批报销申请 对象
        :param reimbursement_approval_ma_id: str
        :return: ReimbursementApprovalMa 对象或 None
        """
        try:
            with self.session_factory() as session:
                reimbursement_approval_ma = session.query(ReimbursementApprovalMa).filter_by(
                    reimbursement_approval_ma_id=reimbursement_approval_ma_id).first()
                if reimbursement_approval_ma:
                    return reimbursement_approval_ma
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None

    def delete_by_reimbursement_approval_ma_id(self, reimbursement_approval_ma_id):
        """
        根据 reimbursement_approval_ma_id 删除经理审批报销申请
        :param reimbursement_approval_ma_id: str
        :return: True（删除成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                reimbursement_approval_ma = session.query(ReimbursementApprovalMa).filter_by(
                    reimbursement_approval_ma_id=reimbursement_approval_ma_id).first()
                if reimbursement_approval_ma:
                    session.delete(reimbursement_approval_ma)
                    session.commit()  # 提交事务
                    return True
                return False  # 经理审批报销申请不存在
        except SQLAlchemyError as e:
            print(f"Database error during delete operation: {str(e)}")
            return False

    def update_by_reimbursement_approval_ma_id(self, reimbursement_approval_ma_update, reimbursement_approval_ma_id):
        """
        根据 reimbursement_approval_ma_id 更新经理审批报销申请信息
        :param reimbursement_approval_ma_id: str
        :param reimbursement_approval_ma_update: ReimbursementApprovalMa 类实例或字典，包含需要更新的审批报销申请属性
        :return: True（更新成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                reimbursement_approval_ma = session.query(ReimbursementApprovalMa).filter_by(
                    reimbursement_approval_ma_id=reimbursement_approval_ma_id).first()
                if reimbursement_approval_ma:
                    # 如果 reimbursement_approval_ma_update 是类实例，转换为字典
                    if reimbursement_approval_ma_update and hasattr(reimbursement_approval_ma_update, 'to_dict'):
                        reimbursement_approval_ma_update = reimbursement_approval_ma_update.to_dict()

                    # 使用新数据更新经理审批报销申请属性
                    for key, value in reimbursement_approval_ma_update.items():
                        if value is not None and hasattr(reimbursement_approval_ma, key):
                            setattr(reimbursement_approval_ma, key, value)

                    session.commit()  # 提交事务
                    return True
                return False  # 经理审批报销申请不存在
        except SQLAlchemyError as e:
            print(f"Database error during update operation: {str(e)}")
            return False

    def select_by_reimbursement_id(self, reimbursement_id):
        """
        根据 reimbursement_id 从数据库获取 经理审批报销申请 对象
        :param reimbursement_id: str
        :return: ReimbursementApprovalMa 对象或 None
        """
        try:
            with self.session_factory() as session:
                reimbursement_approval_ma = session.query(ReimbursementApprovalMa).malter_by(
                    reimbursement_id=reimbursement_id).marst()
                if reimbursement_approval_ma:
                    return reimbursement_approval_ma
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None